package com.jiyun.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiyun.information.ZlDoctorClient;
import com.jiyun.information.ZlInstitutionClient;
import com.jiyun.information.ZlServiceClient;
import com.jiyun.information.ZlTeamClient;
import com.jiyun.mapper.PendingSigningMapper;
import com.jiyun.mapper.SigningInfoMapper;
import com.jiyun.model.information.ZlDoctor;
import com.jiyun.model.information.ZlInstitution;
import com.jiyun.model.information.ZlService;
import com.jiyun.model.information.ZlTeam;
import com.jiyun.model.sign.PendingSigning;
import com.jiyun.model.sign.Residents;
import com.jiyun.model.sign.SigningInfo;
import com.jiyun.model.sign.dto.PendingSigningDto;
import com.jiyun.model.sign.dto.SigningInfoAndResidentsDto;
import com.jiyun.model.sign.dto.SigningInfoQuery;
import com.jiyun.service.IPendingSigningService;
import com.jiyun.service.IResidentsService;
import com.jiyun.service.ISigningInfoService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 针对表【-SigningInfo】的业务操作的Service实现类
 *
 * @author ???
 * @since 2024-09-27
 */
@Service
public class SigningInfoServiceImpl extends ServiceImpl<SigningInfoMapper, SigningInfo> implements ISigningInfoService {

    @Override
    public IPage<SigningInfo> getPageList(SigningInfoQuery query){
        //1.创建查询条件
        QueryWrapper<SigningInfo> qw = new QueryWrapper<>();
        //ToDo 查询条件

        //2.组件分页数据
        IPage<SigningInfo> page = new Page<>(query.getCurrentPage(), query.getPageSize());
        //3.查询
        baseMapper.selectPage(page,qw);
        //4.返回
        return page;
    }

    @Resource
    private ZlInstitutionClient zlInstitutionClient;
    @Resource
    private ZlTeamClient zlTeamClient;
    @Resource
    private ZlDoctorClient zlDoctorClient;
    @Resource
    private ZlServiceClient zlServiceClient;
    @Override
    public SigningInfo findByPendIdSigningInfo(Integer pendingSigningId) {
        LambdaQueryWrapper<SigningInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SigningInfo::getPendingSigningId, pendingSigningId);
        SigningInfo signingInfo = baseMapper.selectOne(wrapper);

        if (signingInfo != null) {
            // 检查每个远程调用返回的对象是否为null
            if (signingInfo.getInstitutionId() != null) {
                ZlInstitution institution = zlInstitutionClient.getById(signingInfo.getInstitutionId());
                if (institution != null) {
                    signingInfo.setInstitutionName(institution.getName());
                }
            }

            if (signingInfo.getTeamId() != null) {
                ZlTeam zlTeam = zlTeamClient.getById(signingInfo.getTeamId());
                if (zlTeam != null) {
                    signingInfo.setTeamName(zlTeam.getName());
                }
            }

            if (signingInfo.getDoctorId() != null) {
                ZlDoctor zlDoctor = zlDoctorClient.getById(signingInfo.getDoctorId());
                if (zlDoctor != null) {
                    signingInfo.setDoctorName(zlDoctor.getDoctorName());
                }
            }

            if (signingInfo.getServiceId() != null) {
                ZlService zlService = zlServiceClient.getById(signingInfo.getServiceId());
                if (zlService != null) {
                    signingInfo.setCost(zlService.getPrice());
                    signingInfo.setServiceName(zlService.getName());
                }
            }
            return signingInfo;
        } else {
            return null;
        }
    }

    @Resource
    private IResidentsService iResidentsService;
    @Resource
    private IPendingSigningService iPendingSigningService;
    @Override
    @Transactional
    public void updateSigningInfo(SigningInfoAndResidentsDto signingInfoAndResidentsDto) {
        // 从 DTO 中提取 SigningInfo 和 Residents 对象
        SigningInfo signingInfo = signingInfoAndResidentsDto.getSigningInfo();
        Residents residents = signingInfoAndResidentsDto.getResidents();

        // 获取待签信息
        PendingSigning pendingSigning = iPendingSigningService.getById(signingInfo.getPendingSigningId());

        // 检查待签信息是否存在
        if (pendingSigning == null) {
            throw new IllegalArgumentException("待签信息不存在");
        }

        // 更新待签信息
        pendingSigning.setServiceId(signingInfo.getServiceId());
        pendingSigning.setTeamId(signingInfo.getTeamId());
        pendingSigning.setInstitutionId(signingInfo.getInstitutionId());
        pendingSigning.setDoctorId(signingInfo.getDoctorId());
        pendingSigning.setUpdateTime(LocalDateTime.now());
        // 获取服务信息并更新成本
        ZlService zlService = zlServiceClient.getById(signingInfo.getServiceId());
        if (zlService == null) {
            throw new IllegalArgumentException("服务信息不存在");
        }
        signingInfo.setCost(zlService.getPrice());

        // 更新待签信息
        iPendingSigningService.updateById(pendingSigning);

        // 更新居民信息
        iResidentsService.update()
                .eq("pending_signing_id", signingInfo.getPendingSigningId())
                .update(residents);

        // 更新签约信息
        baseMapper.updateById(signingInfo);
    }

    @Resource
    private PendingSigningMapper pendingSigningMapper;
    @Scheduled(cron = "0 0 0 * * ?")
    //查询所有生效中的签约信息是否过期
    public void checkExpiration(){
        List<SigningInfo> signingInfoList = baseMapper.selectList(new LambdaQueryWrapper<SigningInfo>().eq(SigningInfo::getStatus, 3));
        for (SigningInfo signingInfo : signingInfoList) {
            LocalDate effectiveDate = signingInfo.getEffectiveDate();
            LocalDate expirationDate = signingInfo.getExpirationDate();
            if (!(effectiveDate.isBefore(LocalDate.now()) && expirationDate.isAfter(LocalDate.now()))) {
                signingInfo.setStatus(4);
                PendingSigning pendingSigning = pendingSigningMapper.selectById(signingInfo.getPendingSigningId());
                pendingSigning.setStatus(4);
                pendingSigningMapper.updateById(pendingSigning);
                baseMapper.updateById(signingInfo);
            }
        }
    }
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Scheduled(cron = "0 0 0 * * ?")
    public void checkPendingSigning(){
        //签约信息已生效的数据离过期距离三天，发信息提醒
        List<SigningInfo> signingInfoList = baseMapper.selectList(new LambdaQueryWrapper<SigningInfo>().eq(SigningInfo::getStatus, 3));
        //判断签约生效中的签约记录是否离过期三天以内
        for (SigningInfo signingInfo : signingInfoList) {
            LocalDate effectiveDate = signingInfo.getEffectiveDate();
            LocalDate expirationDate = signingInfo.getExpirationDate();
            if (expirationDate.minusDays(3).isEqual(LocalDate.now())) {
                // 发送短信提醒
                System.out.println("发送短信提醒");
            }
        }
    }
//    @Scheduled(fixedRate = 5000)
//    public void checkPendingSigning(){
//        List<SigningInfo> signingInfoList = baseMapper.selectList(new LambdaQueryWrapper<SigningInfo>().eq(SigningInfo::getStatus, 3));
//        for (SigningInfo signingInfo : signingInfoList){
//                rabbitTemplate.convertAndSend("aaa", JSON.toJSONString(signingInfo));
//        }
//    }

}
